// 科室评分具体打分
import { FC, useEffect, useState } from 'react'
import { Breadcrumb, Radio, Button, message, Image, Table } from 'antd'
import {
  connect,
  Dispatch,
  Loading,
  EvaluationStateType,
  Location,
  history,
  PointDetailType
} from 'umi'
import type { RadioChangeEvent } from 'antd'
import produce from 'immer'
import { getStorage } from '@/utils'
import { DownOutlined } from '@ant-design/icons'
import FilePreview from '@/components/FilePreview'
import styles from './index.less'

interface IProps {
  evaluationModel: EvaluationStateType
  dispatch: Dispatch
  location: Location
}
const CheckMaterials: FC<IProps> = ({
  dispatch,
  location,
  evaluationModel
}) => {
  const { scoreRules, resourceList } = evaluationModel
  const [filePath, setFilePath] = useState<string>('')
  const [fileType, setFileType] = useState<string>('')

  const [tableData, setTableData] = useState([
    { key: 1, unitName: '', name: '', amby1: '', amby2: '', ruleCode: '' }
  ])

  const { batchCode, type, questionCode, page, parentCode } =
    location.query as {
      batchCode: string
      type: string
      questionCode: string
      page: string
      parentCode: string
    }

  const [breadcrumb, setBreadcrumb] = useState<string[]>([])
  // 获取评审资源
  const getResourceInfo = (): void => {
    dispatch({
      type: 'evaluationModel/function_getSchoolResourceInfo',
      payload: {
        batchCode,
        unitCode: getStorage('schoolCode'),
        questionCode: parentCode
      }
    })
  }

  const handlePoint = (e: RadioChangeEvent) => {
    setTableData(
      produce((draft) => {
        draft.map((item) => {
          item.ruleCode = e.target.value
        })
      })
    )
  }

  const saveScore = (): void => {
    let temp: object[] = tableData
      .map((item) => ({
        questionCode: questionCode,
        ruleCode: item.ruleCode
      }))
      .filter((item) => item.ruleCode)
    if (!temp.length) {
      message.warning('请选择仲裁得分')
      return
    }

    dispatch({
      type: 'evaluationModel/function_saveFinalScore',
      payload: {
        batchCode,
        json: JSON.stringify(temp[0]),
        unitCode: getStorage('schoolCode')
      },
      callback: (response) => {
        if (response.code == 200) {
          message.success('保存成功')
          cancelPoint()
        }
      }
    })
  }

  // 获取打分规则
  const getScoringRules = () => {
    dispatch({
      type: 'evaluationModel/function_getScoringRules',
      payload: {
        ruleCode: '50'
      }
    })
  }

  const setCurrentPreview = (filePath: string) => {
    let type = filePath.substring(filePath.lastIndexOf('.') + 1)
    if (
      [
        'ppt',
        'pptx',
        'xlsx',
        'docx',
        'xls',
        'doc',
        'zip',
        'rar',
        '7z'
      ].includes(type)
    ) {
      window.open(filePath)
      return
    }
    setFileType(type)
    setFilePath(filePath)
  }

  const cancelPoint = () => {
    history.replace({
      pathname: '/arbitration/resource',
      query: {
        batchCode
      }
    })
  }

  useEffect(() => {
    getResourceInfo()
    setBreadcrumb(getStorage('breadcrumb')!.split('->').slice(0, -1))
    dispatch({
      type: 'evaluationModel/function_getPointInfoByParentCode',
      payload: {
        batchCode: batchCode,
        parentCode,
        type
      }
    })
    getScoringRules()
  }, [])

  // 默认选中第一个非office和压缩文件材料
  useEffect(() => {
    let type = ''
    let path = ''
    try {
      resourceList.files?.forEach((item) => {
        if (item.children) {
          item.children.forEach((v: any) => {
            if (
              ![
                'ppt',
                'pptx',
                'xlsx',
                'docx',
                'xls',
                'doc',
                'zip',
                'rar',
                '7z'
              ].includes(v.url.substring(v.url.lastIndexOf('.') + 1))
            ) {
              path = v.url
              type = v.url.substring(v.url.lastIndexOf('.') + 1)
              throw '找到了'
            }
          })
        }
      })
    } catch (err) {
    } finally {
      if (path) {
        setFilePath(path)
        setFileType(type)
      }
    }
    return () => {
      setFilePath('')
      setFileType('')
    }
  }, [resourceList])

  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (text: string, record: any, index: number) => (
        <span>{(index + 1).toString().padStart(2, '0')}</span>
      )
    },
    {
      title: '学校名称',
      dataIndex: 'unitName',
      key: 'unitName',
      align: 'center',
      render: () => {
        return <span>{getStorage('schoolName')}</span>
      }
    },
    {
      title: '指标名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      render: () => {
        return <span>{getStorage('breadcrumb')}</span>
      }
    },
    {
      title: '一评得分',
      dataIndex: 'lamby1',
      key: 'lamby1',
      render: (text: string, record: any, index: number) => {
        return (
          <Radio.Group value={getStorage('lamby1')}>
            {scoreRules.map((item) => (
              <Radio value={item.code} key={item.code}>
                {item.name}
              </Radio>
            ))}
          </Radio.Group>
        )
      },
      align: 'center'
    },
    {
      title: '二评得分',
      dataIndex: 'lamby2',
      key: 'lamby2',
      render: (text: string, record: any, index: number) => {
        return (
          <Radio.Group value={getStorage('lamby2')}>
            {scoreRules.map((item) => (
              <Radio value={item.code} key={item.code}>
                {item.name}
              </Radio>
            ))}
          </Radio.Group>
        )
      },
      align: 'center'
    },
    {
      title: '仲裁得分',
      dataIndex: 'lamby2',
      key: 'lamby2',
      render: (text: string, record: any, index: number) => {
        return (
          <Radio.Group value={record.ruleCode} onChange={(e) => handlePoint(e)}>
            {scoreRules.map((item) => (
              <Radio value={item.code} key={item.code}>
                {item.name}
              </Radio>
            ))}
          </Radio.Group>
        )
      },
      align: 'center'
    }
  ]

  return (
    <>
      <div className={styles['outer-wrapper']}>
        <div className={styles['main-content']}>
          <div className={styles['left-pannel']}>
            <div className={styles['module-title']}>佐证材料列表</div>
            <div className={styles['module-content']}>
              {resourceList?.files?.map((item) => (
                <div key={item.type} className={styles['type-item']}>
                  <div className={styles['material-type']}>
                    <span>{item.type}</span>
                    <DownOutlined />
                  </div>
                  <ul className={styles['material-wrapper']}>
                    {item.children?.map((v: any) => (
                      <li
                        key={v.fileName}
                        className={
                          filePath === v.url
                            ? [
                                `${styles['material-item']}`,
                                `${styles['active-material']}`
                              ].join(' ')
                            : styles['material-item']
                        }
                        onClick={() => setCurrentPreview(v.url)}
                      >
                        {v.fileName}
                      </li>
                    ))}
                  </ul>
                </div>
              ))}
            </div>
          </div>
          <div className={styles['right-pannel']}>
            <div className={styles['material-preview']}>
              <div className={styles['module-title']}>佐证材料预览</div>
              <div className={styles['module-content']}>
                <div className={styles['preview-wrapper']}>
                  {['jpg', 'png', 'jpeg', 'gif', 'webp'].includes(fileType) ? (
                    <Image src={`${filePath}`} />
                  ) : ['mp4', 'webm', 'ogg'].includes(fileType) ? (
                    <video
                      src={`${filePath}`}
                      controls
                      width="100%"
                      height="100%"
                    >
                      您的浏览器不支持 video 标签。
                    </video>
                  ) : ['pdf'].includes(fileType) ? (
                    <iframe src={filePath} width="100%" height="100%" />
                  ) : ['mp3', 'wav'].includes(fileType) ? (
                    <audio src={filePath} controls muted loop />
                  ) : (
                    <FilePreview fileType={fileType} filePath={filePath} />
                  )}
                </div>
              </div>
            </div>
            <div className={styles['mark-pannel']}>
              <div className={styles['module-title']}>
                <div className={styles.breadcrumb}>
                  <Breadcrumb separator=">">
                    {breadcrumb?.map((item) => (
                      <Breadcrumb.Item key={item}>{item}</Breadcrumb.Item>
                    ))}
                  </Breadcrumb>
                </div>
                <div className={styles.rules}>
                  评分规则：符合（满分）、基本符合（半分）、不符合（0分）
                </div>
              </div>
              <div className={styles['module-content']}>
                <Table
                  dataSource={tableData}
                  columns={columns}
                  pagination={false}
                  bordered
                />

                <div className={styles['btn-wrapper']}>
                  <Button onClick={() => cancelPoint()}>取消</Button>
                  <Button type="primary" onClick={() => saveScore()}>
                    提交
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <p className={styles['copy-right']}>
          Copyright@ 2016 成都乐培生科技有限公司 蜀ICP备15018125号
        </p>
      </div>
    </>
  )
}

const mapStateToProps = ({
  evaluationModel,
  loading
}: {
  evaluationModel: EvaluationStateType
  loading: Loading
}) => {
  return {
    evaluationModel,
    evaluationLoding: loading.models.evaluationModel
  }
}

export default connect(mapStateToProps)(CheckMaterials)
